// package GIN框架中的路由层
package router

import (
	"fmt"
	"net/http"
	"osiris/controller"
	"osiris/logger"

	"github.com/gin-gonic/gin"
	"strconv"
)

// var
//
//	@param Server http服务器（GIN）
var (
	Server *http.Server
)

// MakeHttpServer 创建http服务器
//
//	@param httpServerPort 端口
func MakeHttpServer(httpServerPort int) {
	Server = &http.Server{
		Addr:    ":" + strconv.Itoa(httpServerPort),
		Handler: router(),
	}
}

// router 创建路由
//
//	@return *gin.Engine
func router() *gin.Engine {
	router := gin.Default()

	//自定义日志
	router.Use(gin.LoggerWithConfig(logger.LoggerToFile()))
	router.Use(logger.Recover)

	blockchainGroup := router.Group("/blockchain")
	{
		blockchainGroup.GET("/get", controller.BlockchainController{}.GetHandler)
	}

	accountGroup := router.Group("/account")
	{
		accountGroup.GET("/register", controller.AccountController{}.RegisterHandler)
		accountGroup.GET("/get/:chainID/:addr", controller.AccountController{}.GetHandler)
		accountGroup.POST("/tx", controller.AccountController{}.TxHandler)
	}

	peerGroup := router.Group("/peer")
	{
		peerGroup.GET("/get/:chainID/:peerID", controller.PeerController{}.GetHandler)
	}

	//test
	router.GET("/ping", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
		fmt.Println("ping!")
	})

	testGroup := router.Group("/test")
	{
		testGroup.POST("/tx/sign", controller.TestController{}.TxDataSignHandler)
	}

	return router
}
